<?php

namespace app\common\model\banxi\core;

use app\common\model\common\BaseModel;
use think\exception\ValidateException;
use think\model\concern\SoftDelete;

/**
 * 账户课时表
 */
class CoreTrialClassConfig extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_core_trial_class_config';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'buyPageImageList'
    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];

    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------

    public function getBuyPageImageListAttr($value, $data)
    {
        $value = $value ?: ($data['buyPageImage'] ?? '');
        return $value ? explode(',', $value) : [];
    }


    //-----------------------------------------------------------------------------------
    //｜                                   处理办法                                       ｜
    //-----------------------------------------------------------------------------------


    public function getListPage(array $where, string $page = '1', int $limit = 10)
    {
        return $this->where($where)
            ->paginate([
                'page' => $page,
                'list_rows' => $limit
            ]);
    }

    public function getInfo(array $where)
    {
        return $this->where($where)->find();
    }

    public function saveOrUpdate(array $data)
    {
        $data['buyPageImage'] = implode(',', $data['buyPageImageList'] ?? []);
        $id = $data['id'] ?? null;
        if ($id) {
            $info = $this->where(['id' => $id])->find();
            if (!$info) {
                throw new ValidateException('配置不存在');
            }
            $info->save($data);
        } else {
            $this->save($data);
        }
        return true;
    }

    public function del($ids)
    {
        return self::destroy(function ($query) use ($ids) {
            $query->whereIn('id', $ids);
        });
    }

    public function getConfigInfo()
    {
        return $this->order(['id'=>'desc'])->find();
    }
    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------


}